<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val)"></user-table-config>
      </template>
      <template slot-scope="{ row }" slot="menu">
        <el-button type="text" icon="el-icon-view" size="small" @click.stop="handleView(row)">详情</el-button>
        <el-button type="text" icon="el-icon-edit" size="small" @click.stop="handleEdit(row)" v-if="permission.preProcessingRuleConfig_edit">编辑</el-button>
        <el-button type="text" size="small" icon="el-icon-delete" v-if="permission.preProcessingRuleConfig_delete" @click="rowDel(row)">删除</el-button>
        <el-button type="text" icon="el-icon-edit" size="small" @click.stop="openSop(row)" v-if="permission.preProcessingRuleConfig_viewESOP">ESOP预览</el-button>
      </template>
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" @click="addBtn" v-if="permission.preProcessingRuleConfig_add">新 增</el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" v-if="permission.preProcessingRuleConfig_delete" @click="handleDelete">删 除 </el-button>
      </template>
    </avue-crud>
    <el-dialog ref="dialog" :title="dialogTitle" append-to-body :visible.sync="showDialog" :close-on-click-modal="false" @close="dialogClose" top="5vh" width="60%">
      <h3 class="custom-title"><i class="el-icon-vertical-bar mr10"></i>基础信息</h3>
      <avue-form ref="form" v-if="showDialog" v-model="form" :option="dialogOption">
        <template slot="attachFile">
          <div v-if="dialogTitle != '详情'">
            <el-upload
              class="upload-demo"
              drag
              action="/api/blade-resource/oss/endpoint/put-file-attach?attachType=preprocess_esop"
              :headers="headersObj"
              accept=".pdf"
              :limit="1"
              :before-upload="uploadBefore"
              :on-success="uploadAfter"
              :file-list="fileList"
              :on-remove="uploadDelete"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </el-upload>
          </div>
          <div v-else>
            <span>{{ form.originalName }}</span>
          </div>
        </template>
      </avue-form>
      <h3 class="custom-title"><i class="el-icon-vertical-bar mr10"></i>前加工物料配置表</h3>
      <avue-crud
        :option="partInfoOption"
        :table-loading="loading"
        :data="partInfoList"
        ref="partInfoCrud"
        @row-save="partInfoRowSave"
        @row-update="partInfoRowUpdate"
        @row-del="partInfoRowDel"
        @selection-change="partInfoSelectionChange"
      >
        <template slot="menuLeft">
          <el-button v-if="dialogTitle != '详情'" type="primary" size="small" @click="addBom">添加BOM</el-button>
          <el-button v-if="dialogTitle != '详情'" type="primary" size="small" @click="addMaterial">添加物料</el-button>
          <el-button v-if="dialogTitle != '详情'" type="danger" size="small" icon="el-icon-delete" @click="productInfoDelete">删 除</el-button>
        </template>
      </avue-crud>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="dialogTitle != '详情'" type="primary" size="small" @click="save"><i class="el-icon-check"></i><span>保 存</span></el-button>
        <el-button size="small" @click="showDialog = false"><i class="el-icon-circle-close"></i><span>关 闭</span></el-button>
      </span>
    </el-dialog>
    <el-dialog class="showEsopDialog" v-dragDirectives ref="dialog" title="查看SOP" append-to-body :visible.sync="showEsopDialog" :close-on-click-modal="false" top="5vh">
      <iframe v-if="showEsopDialog" ref="pdf" :src="pdfUrl" width="100%" height="100%"></iframe>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="showEsopDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :key="timer" :option="tableOption" @getSelectedRows="getSelectedRows" @newKey="newKey"></common-modal-template>
  </basic-container>
</template>

<script>
import { getList, submit, getDetail, remove } from '@/api/product/preProcessingRuleConfig';
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template';
import { getList as getBomList } from '@/api/admin/bom';
import website from '@/config/website';
import { Base64 } from 'js-base64';
import { getToken } from '@/util/auth';
import { downLoad } from '@/api/resource/attach';
export default {
  name: 'ProductPreProcessingRuleConfig',
  components: {
    userTableConfig,
    CommonModalTemplate
  },
  mixins: [userConfig()],
  data() {
    var validateQuantity = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入单位用量'));
      } else {
        if (value <= 0) {
          callback(new Error('单位用量不能小于等于0'));
        } else {
          callback();
        }
      }
    };
    return {
      form: {},
      query: {},
      timer: new Date().getTime(),
      loading: false,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        editBtn: false,
        delBtn: false,
        selection: true,
        dialogClickModal: false,
        columnBtn: false,
        menuWidth: 300,
        column: [
          {
            label: '产品编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '产品名称',
            prop: 'partName',
            search: true
          },
          {
            label: '产品型号',
            prop: 'partModel',
            search: true
          },
          {
            label: '前加工物料种类',
            prop: 'partCount'
          },
          {
            label: '最近更新时间',
            prop: 'updateTime'
          }
        ]
      },
      data: [],
      dialogTitle: '新增',
      showDialog: false,
      dialogOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '150',
        column: [
          {
            label: '产品编码',
            prop: 'partNo',
            span: 8,
            type: 'search',
            placeholder: '请选择 产品编码',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择产品编码',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              if (this.dialogTitle === '新增') {
                this.openProductCommonModal();
              }
            }
          },
          {
            label: '产品名称',
            prop: 'partName',
            span: 8,
            disabled: true
          },
          {
            label: '产品型号',
            prop: 'partModel',
            span: 8,
            disabled: true
          },
          {
            label: 'SOP文件',
            prop: 'attachFile',
            span: 24,
            rules: [
              {
                required: true,
                message: '请选择SOP文件',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      fileList: [],
      partInfoOption: {
        height: 300,
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        viewBtn: false,
        selection: true,
        dialogClickModal: false,
        refreshBtn: false,
        columnBtn: false,
        cellBtn: true,
        menuWidth: 150,
        column: [
          {
            label: '物料编码',
            prop: 'partNo'
          },
          {
            label: '物料名称',
            prop: 'partName'
          },
          {
            label: '物料型号',
            prop: 'partModel'
          },
          {
            label: '单位用量',
            prop: 'unitQuantity',
            cell: true,
            type: 'number',
            rules: [{ required: true, validator: validateQuantity, trigger: 'blur' }]
          },
          {
            label: '加工规则',
            prop: 'processRule',
            cell: true,
            width: 300
          }
        ]
      },
      partInfoList: [],
      partInfoSelectionList: [],
      tableOption: {},
      timer: new Date().getTime(),
      showEsopDialog: false,
      pdfUrl: ''
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.stationManage_add, false),
        delBtn: this.vaildData(this.permission.stationManage_delete, false),
        editBtn: this.vaildData(this.permission.stationManage_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    },
    headersObj() {
      let header = { Authorization: `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}` };
      header['Blade-Auth'] = 'bearer ' + getToken();
      return header;
    },
    partIds() {
      let ids = [];
      this.partInfoSelectionList.forEach((ele) => {
        ids.push(ele.partMasterId);
      });
      return ids;
    }
  },
  methods: {
    /**
     * 表单重置
     */
    emptytChange() {},

    reset() {
      this.addDialog = false;
      this.$refs.addProperties.resetForm();
    },
    addBtn() {
      this.dialogTitle = '新增';
      this.showDialog = true;
      this.$nextTick(() => {
        this.$refs.form.allDisabled = false;
        this.partInfoOption.menu = true;
      });
    },
    dialogClose() {
      this.$refs.form.resetFields();
      this.form = {};
      this.fileList = [];
      this.partInfoList = [];
      this.showDialog = false;
    },
    handleEdit(row) {
      this.showDialog = true;
      this.dialogTitle = '编辑';
      this.$nextTick(() => {
        this.$refs.form.allDisabled = false;
        this.partInfoOption.menu = true;
      });
      getDetail(row.id).then((res) => {
        this.form = this._get(res, 'data.data', {});
        this.form.attachFile = [{ attachId: this.form.attachId, attachName: this.form.originalName, link: this.form.attachUrl }];
        this.fileList = [{ name: this.form.originalName, url: this.form.attachUrl }];
        this.partInfoList = this.form.items;
      });
    },
    handleView(row) {
      this.showDialog = true;
      this.dialogTitle = '详情';
      this.$nextTick(() => {
        this.$refs.form.allDisabled = true;
        this.partInfoOption.menu = false;
      });
      getDetail(row.id).then((res) => {
        this.form = this._get(res, 'data.data', {});
        this.form.attachFile = [{ attachId: this.form.attachId, attachName: this.form.originalName, link: this.form.attachUrl }];
        this.fileList = [{ name: this.form.originalName, url: this.form.attachUrl }];
        this.partInfoList = this.form.items;
      });
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove([row.id]);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete(row) {
      if (this.selectionList.length === 0 && !row.id) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    /**
     * 打开avue-crud之前的调用
     */
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getWorkStationDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    partInfoSelectionChange(list) {
      this.partInfoSelectionList = list;
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    uploadBefore(file) {
      if (file.name.split('.')[1] != 'pdf') {
        this.$message({
          type: 'warning',
          message: '只能上传pdf文件！'
        });
        return false;
      }
    },
    uploadAfter(res, done, loading, column) {
      this.form.attachFile = [];
      this.form.attachFile.push({
        attachId: res.data.attachId,
        link: res.data.link,
        attachName: res.data.originalName
      });
    },
    uploadDelete(file, column) {
      this.form.attachFile.splice(0, 1);
    },
    /**
     * 打开物料选择模态框
     */
    openProductCommonModal() {
      this.modalName = 'productModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择产品（双击进行选择）',
        url: 'api/mes-admin/partmaster/query-for-preprocess',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '物料编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '物料名称',
            prop: 'name',
            search: true
          },
          {
            label: '物料分类',
            prop: 'categoryName'
          },
          {
            label: '物料型号',
            prop: 'partModel'
          },
          {
            label: '物料类型',
            prop: 'partType',
            type: 'select',
            dicData: [
              {
                label: '半成品',
                value: 'SEMIFINISHED'
              },
              {
                label: '成品',
                value: 'PRODUCT'
              }
            ]
          },
          {
            label: '描述',
            prop: 'description'
          }
        ]
      };
    },
    /**
     * 添加物料
     */
    addMaterial() {
      this.modalName = 'partModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择物料',
        url: '/api/mes-admin/part-master/page?materialAndSemifinished=true',
        isPage: true,
        rowSelectionType: 'multiple',
        isDefaultLoad: true,
        columnDefs: [
          {
            label: '物料编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '物料名称',
            prop: 'name',
            search: true
          },
          {
            label: '物料分类',
            prop: 'categoryName'
          },
          {
            label: '物料型号',
            prop: 'partModel'
          },
          {
            label: '描述',
            prop: 'description'
          }
        ]
      };
    },
    addBom() {
      if (!this.form.partNo) {
        this.$message({
          type: 'warning',
          message: '请先选择产品编码！'
        });
        return;
      }
      getBomList(1, 10000, { partNo: this.form.partNo, sourceType: 'ERP', isAll: true }).then((res) => {
        let bomList = this._get(res, 'data.data.records', []);
        if (bomList.length > 0) {
          bomList = this._map(bomList, (item) => {
            return {
              label: item.bomVersion,
              value: item.id
            };
          });
          let bomId = this._get(bomList, '[0].value', '');
          this.openBomPart(bomList, bomId);
        } else {
          this.$message({
            type: 'warning',
            message: '请先配置相应的产品BOM！'
          });
        }
      });
    },
    openBomPart(bomList, bomId) {
      this.modalName = 'bomModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择BOM物料信息（双击进行选择）',
        url: '/api/mes-admin/bom/detail/part-page',
        isPage: true,
        index: true,
        selection: true,
        isDefaultLoad: true,
        // tableTitle: '替代料',
        rowSelectionType: 'multiple',
        columnDefs: [
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '类型',
            prop: 'categoryId',
            type: 'tree',
            dicUrl: '/api/mes-admin/part-category/tree',
            props: {
              label: 'title',
              value: 'id'
            }
          },
          {
            label: '型号',
            prop: 'partModel'
          },
          {
            label: '用量',
            prop: 'unitQty'
          },
          {
            label: 'BOM版本',
            prop: 'bomId',
            search: true,
            type: 'select',
            dicData: bomList,
            searchValue: bomId,
            hide: true
          }
        ]
      };
    },
    /**
     * 双击模态框行
     */
    getSelectedRows(row) {
      switch (this.modalName) {
        case 'productModal':
          this.form.partMasterId = row.id;
          this.form.partNo = row.partNo;
          this.form.partName = row.name;
          this.form.partModel = row.partModel;
          break;
        case 'partModal':
          for (let i = 0; i < row.length; i++) {
            this.partInfoList.push({
              $cellEdit: true,
              partMasterId: row[i].id,
              partNo: row[i].partNo,
              partName: row[i].name,
              partModel: row[i].partModel,
              unitQuantity: undefined
            });
          }
          break;
        case 'bomModal':
          for (let i = 0; i < row.length; i++) {
            this.partInfoList.push({
              $cellEdit: true,
              partMasterId: row[i].id,
              partNo: row[i].partNo,
              partName: row[i].name,
              partModel: row[i].partModel,
              unitQuantity: row[i].unitQty
            });
          }
          break;
        default:
          break;
      }
    },
    newKey() {
      this.timer = new Date().getTime();
    },
    partInfoRowSave(form, done) {
      done();
    },
    partInfoRowUpdate(form, index, done) {
      done();
    },
    partInfoRowDel(row, index) {
      this.partInfoList.splice(index, 1);
      //   if (row.id) {
      //     this.materialControlsDeleteIds.push(row.id);
      //   }
    },
    save() {
      this.$refs.form.validate((valid, done) => {
        if (valid) {
          if (this.partInfoList.length === 0) {
            this.$message.warning('请选择前加工物料配置！');
            return;
          }
          for (let i = 0; i < this.partInfoList.length; i++) {
            if (!this.partInfoList[i].unitQuantity) {
              this.$message.warning(`物料编码${this.partInfoList[i].partNo}的单位用量不能为空！`);
              return;
            }
          }
          let params = {
            partNo: this.form.partNo,
            partName: this.form.partName,
            partMasterId: this.form.partMasterId,
            partModel: this.form.partModel,
            attachId: this.form.attachFile[0] ? this.form.attachFile[0].attachId : '',
            items: this.partInfoList
          };
          if (this.dialogTitle === '编辑') {
            params['id'] = this.form.id;
          }
          submit(params).then((res) => {
            this.showDialog = false;
            this.$message.success(res.data.msg);
            this.onLoad(this.page);
          });
        }
      });
    },
    productInfoDelete() {
      if (this.partInfoSelectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this._forEach(this.partIds, (item) => {
          let obj = this._find(this.partInfoList, { partMasterId: item });
          let index = this._findIndex(this.partInfoList, obj);
          this.partInfoList.splice(index, 1);
        });
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        this.$refs.partInfoCrud.toggleSelection();
      });
    },
    openSop(row) {
      if (!row.attachUrl || row.attachUrl == null) {
        this.$message({
          type: 'warning',
          message: '未选择SOP附件，请先点编辑选择SOP文件！'
        });
        return;
      }
      this.showEsopDialog = true;
      this.downLoadEsop(row.attachUrl);
    },
    downLoadEsop(pdfUrl) {
      downLoad({ link: pdfUrl }).then(
        (res) => {
          // var blob = new Blob([res.data], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
          let fileURL = null;
          var blob = new Blob([res.data], { type: 'application/pdf' });
          if (window.createObjectURL != undefined) {
            // basic
            fileURL = window.createObjectURL(blob);
          } else if (window.webkitURL != undefined) {
            // webkit or chrome
            try {
              fileURL = window.webkitURL.createObjectURL(blob);
            } catch (error) {
              console.log(error);
            }
          } else if (window.URL != undefined) {
            // mozilla(firefox)
            try {
              fileURL = window.URL.createObjectURL(blob);
            } catch (error) {
              console.log(error);
            }
          }
          this.pdfUrl = '/pdf/web/viewer.html?file=' + encodeURIComponent(fileURL);
        },
        (error) => {}
      );
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .upload-demo {
  width: 100%;
  .el-upload {
    width: 100%;
    .el-upload-dragger {
      width: 100%;
    }
  }
}
.showEsopDialog ::v-deep .el-dialog__body {
  height: 76vh;
}
</style>
